﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataObjects;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace GT5RemoteMobile.Services
{
    public class HelperRequests
    {

        public static Profile GetProfile(string user, string jsessionId)
        {
            // hack to get a proper jsession id from gran-turismo.com
            HttpWebRequest profileRequest = WebRequest.Create(new Uri("https://us.gran-turismo.com/us/api/gt5/profile/")) as HttpWebRequest;
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
#if(DEBUG)
            //profileRequest.Proxy = new WebProxy("localhost", 8888);
#endif
            profileRequest.Method = "POST";
            StreamWriter writer = new StreamWriter(profileRequest.GetRequestStream());

            writer.Write("online_id=" + user);
            writer.Close();
            profileRequest.CookieContainer = new CookieContainer();
            profileRequest.Headers.Add("Cookie", jsessionId);
            profileRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            profileRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            //foreach (string c in Request.Cookies)
            //{
            //    Cookie cookie = new Cookie(Request.Cookies[c].Name, Request.Cookies[c].Value, Request.Cookies[c].Path, Request.Cookies[c].Domain);
            //    profileRequest.CookieContainer.Add(cookie);
            //}
            using (HttpWebResponse response = profileRequest.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string jsonData = reader.ReadToEnd();
                return JsonConvert.DeserializeObject<Profile>(jsonData);
            }
        }
    }
}